package com.atguigu.lease.web.app.custom.interceptor;

import com.atguigu.lease.common.context.LoginUser;
import com.atguigu.lease.common.utils.JwtUtil;
import com.atguigu.lease.common.utils.ThreadLocalUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class GlobalInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        System.out.println("--------------拦截前----------------");
        String token = request.getHeader("Access_token");
        Claims claims = JwtUtil.parseToken(token);
        Long id = claims.get("userId", Long.class);
        String username = claims.get("username", String.class);
        LoginUser loginUser = new LoginUser(id,username);
        ThreadLocalUtil.threadLocal.set(loginUser);

        return true;

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        ThreadLocalUtil.threadLocal.remove();
    }
}